import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import Markdown from 'unplugin-vue-markdown/vite';
import MarkdownItShiki from '@shikijs/markdown-it';
import Pages from 'vite-plugin-pages';
import tailwindcss from '@tailwindcss/vite';

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue({
      include: [/\.vue$/, /\.md$/],
    }),
    Markdown({
      wrapperComponent: (id) => {
        return id.includes('/markdown/') ? 'WrapperPost' : undefined;
      },
      wrapperClasses: 'markdown-content',
      async markdownItSetup(md) {
        md.use(
          await MarkdownItShiki({
            themes: {
              dark: 'one-dark-pro',
              light: 'one-dark-pro',
            },
            cssVariablePrefix: '--s-',
          })
        );

        md.renderer.rules.image = function (tokens, idx, options, env, self) {
          const token = tokens[idx];
          const attrs = token.attrs || [];

          let hasClass = false;
          for (let i = 0; i < attrs.length; i++) {
            if (attrs[i][0] === 'class') {
              attrs[i][1] += ' zoom-img';
              hasClass = true;
              break;
            }
          }
          if (!hasClass) {
            attrs.push(['class', 'zoom-img']);
          }

          const alt = token.content || '';
          const altIndex = token.attrIndex('alt');
          if (altIndex < 0) {
            attrs.push(['alt', alt]);
          } else {
            attrs[altIndex][1] = alt;
          }
          const attributes = self.renderAttrs({ attrs: attrs });
          return `<img ${attributes}>`;
        };
      },
    }),
    Pages({
      extensions: ['vue', 'md'],
      dirs: [{ dir: 'src/markdown', baseRoute: 'blog' }],
    }),
    tailwindcss(),
  ],
});
